﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace PlusOne.Reflection
{
	public class AnonymousObjectWrapper
	{
		private readonly object innerObject;

		private readonly IDictionary<string, object> values;

		internal AnonymousObjectWrapper(object anonObjValue)
		{
			innerObject = anonObjValue;
			var pairs =
				from prop in
					anonObjValue.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)
				select new {name = prop.Name, value = prop.GetValue(anonObjValue, null)};

			values = pairs.ToDictionary(x => x.name, x => x.value);
		}

		public object InnerObject
		{
			get
			{
				return innerObject;
			}
		}

		public object this[string name]
		{
			get
			{
				return values[name];
			}
		}

		public IEnumerable<KeyValuePair<string, object>> Pairs
		{
			get
			{
				return values;
			}
		}

		public static AnonymousObjectWrapper Define(object anonObjValue)
		{
			return new AnonymousObjectWrapper(anonObjValue);
		}
	}
}